<template>
	<view class="content-box">
		<navbar :leftIcon="true" bgColor="rgba(48, 129, 236, 1)" color="#fff">
			<template #left>
				<view class="left-icon">
					<image src="/static/icon/left-white.svg"></image>
				</view>
			</template>
			<template #title>
				<!-- <text>{{t('market.cpxq')}}</text> -->
				<view class="title-box">
					<view class="title">{{ stockDetail.nameZh || 'ETH/USDT' }}/USDT</view>
					<view class="change-box">
						（<text class="change" :class="getChangeClass(realtimeData.changePercent)">{{ formatChangePercent(realtimeData.changePercent) }}</text>）
					</view>
				</view>
			</template>
			<template #right>
				<view class="collect-icon" @click="changeCollect">
					<image :src="`/static/icon/${isCollect ? 'icon5' : 'icon4'}.svg`" class="icon"></image>
				</view>
			</template>
		</navbar>

		<!-- 价格信息区域 -->
		<view class="price-info">
			<view class="coin-icon">
				<image :src="iconPath" class="icon"></image>
			</view>
			<view class="info-box">
				<view class="price-value">{{ realtimeData.lastPrice || '0.00' }}</view>
				<view class="price-details">
					<view class="price-row">
						<text class="label">O:</text>
						<text class="value">{{ realtimeData.open || '--' }}</text>
						<text class="label">H:</text>
						<text class="value">{{ realtimeData.high || '--' }}</text>
					</view>
					<view class="price-row">
						<text class="label">L:</text>
						<text class="value">{{ realtimeData.low || '--' }}</text>
						<text class="label">C:</text>
						<text class="value">{{ realtimeData.close || '--' }}</text>
					</view>
				</view>
			</view>
			<!-- 时间选择器 -->
			<view class="time-selector">
				<view class="time-item" :class="{active: activeTime === '1m'}" @click="setActiveTime('1m')">1m</view>
				<view class="time-item" :class="{active: activeTime === '5m'}" @click="setActiveTime('5m')">5m</view>
				<view class="time-item" :class="{active: activeTime === '30m'}" @click="setActiveTime('30m')">30m</view>
				<view class="time-item" :class="{active: activeTime === '60m'}" @click="setActiveTime('60m')">60m</view>
				<view class="time-item" :class="{active: activeTime === '1D'}" @click="setActiveTime('1D')">1D</view>
				<view class="time-item" :class="{active: activeTime === '1W'}" @click="setActiveTime('1W')">1W</view>
				<view class="time-item" :class="{active: activeTime === '1M'}" @click="setActiveTime('1M')">1M</view>
				<!-- <view class="chart-type"> -->
				<view class="chart-icon" v-if="chartType === 'candle'" :class="{active: chartType === 'candle'}"
					@click="setChartType('line')">
					<image src="/static/icon/icon1.svg" class="icon"></image>
				</view>
				<view class="chart-icon" v-else :class="{active: chartType === 'line'}" @click="setChartType('candle')">
					<image src="/static/icon/icon2.svg" class="icon"></image>
				</view>
				<view class="chart-icon" @click="showIndicators">
					<image src="/static/icon/icon3.svg" class="icon"></image>
				</view>
				<!-- </view> -->
			</view>
		</view>

		<!-- 图表区域 -->
		<view class="chart-container">
			<TradeComponent 
				:klineData="klineData" 
				:chartType="chartType"
				:timeInterval="activeTime"
				idtemp="1"
				decimal="8"
				ref="tradeRef"
				@kline-click="handleKlineClick"
				@price-highlight="handlePriceHighlight">
			</TradeComponent>
			<!-- Y轴价格显示区域 -->
			<view class="y-axis-price" :class="{ 'candle-chart': isCandleChart }" v-if="showYAxisPrice">
				{{ yAxisPrice }}
			</view>
		</view>

		<!-- 持仓/已平按钮 -->
		<view class="position-tabs">
			<view class="border-box">
				<view class="tab" :class="{active: activeTab === 'holding'}" @click="setActiveTab('holding')">
					{{ t('market.cczw') }}
				</view>
				<view class="tab" :class="{active: activeTab === 'closed'}" @click="setActiveTab('closed')">
					{{ t('market.ypz') }}
				</view>
			</view>
		</view>

		<!-- 持仓列表 -->
		<view class="position-list">
			<!-- 空数据状态 -->
			<view v-if="positionList.length === 0" class="empty-container">
				<text>暂时没有数据</text>
			</view>
			<!-- 持仓数据 -->
			<view class="position-item" v-else v-for="(item, index) in positionList" :key="index" @click="goToPositionDetail(item.id)">
				<view class="position-header">
					<view class="symbol-info">
						<text class="symbol">{{ item.symbol }}</text>
						<view class="direction-tag" :class="item.direction === 1 ? 'up' : 'down'">
							<image :src="item.direction === 1 ? '/static/icon/up-icon2.svg' : '/static/icon/down-icon2.svg'"
								mode="aspectFit"></image>
						</view>
					</view>
					<view class="right">
						<view class="progress-bar">
							<view class="progress-fill" :style="{ width: item.progressWidth }"></view>
						</view>
						<view class="time-info">
							<text>{{ item.time }}</text>
						</view>
					</view>
				</view>
				<view class="position-details">
					<view class="detail-column">
						<text class="label">{{ t('position.kyjg') }}</text>
						<text class="value">{{ item.openPrice }}</text>
					</view>
					<view class="detail-column">
						<text class="label">{{ t('position.xdsl') }}</text>
						<text class="value">{{ item.amount }}</text>
					</view>
					<view class="detail-column">
						<text class="label">{{ t('position.syl') }}</text>
						<text class="value"
							:class="item.profitRate.startsWith('+') ? 'profit' : 'loss'">{{ item.profitRate }}</text>
					</view>
					<view class="detail-column">
						<text class="label">{{ t('position.fdsy') }}</text>
						<text class="value"
							:class="item.floatingProfit.startsWith('+') ? 'profit' : 'loss'">{{ item.floatingProfit }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 交易按钮 -->
		<view class="trade-buttons">
			<view class="buy-button" @click="openBuyPopup('1')">{{ t('market.ml') }}</view>
			<view class="sell-button" @click="openBuyPopup('0')">{{ t('market.md') }}</view>
		</view>
		<!-- 交易弹窗 -->
		<u-popup :show="isShowBuy" :round="45" mode="bottom" @close="closePopup">
			<view class="popup-box">
				<view class="top-icon"></view>
				<view class="top">
					<view class="left">
						<image :src="iconPath" mode=""></image>
						<view class="name-box">
							<view class="name">{{ stockDetail.nameZh || 'ETH/USDT' }}/USDT</view>
							<view class="change" :class="getChangeClass(stockDetail.stockInfo?.market?.changePercent)">{{ formatChangePercent(stockDetail.stockInfo?.market?.changePercent) }}</view>
						</view>
					</view>
					<view class="right">
						<view class="price">{{ stockDetail.stockInfo?.market?.lastPrice || '--' }}</view>
						<view class="buy-text">
							买入方向
							<image v-if="isUpOrDown=='1'" src="/static/icon/up-icon2.svg" mode=""></image>
							<image v-if="isUpOrDown=='0'" src="/static/icon/down-icon2.svg" mode=""></image>
						</view>
					</view>
				</view>
				<view class="middle-box">
					<view class="item-box" v-for="(item,index) in revenueList" :key="index" :class="{active:isSelectBuy==index}"
						@click="chooseBuy(index)">
						<view class="time">{{item.time}}</view>
						<view class="revenue">{{ t('market.syls') }}：{{item.revenue}}</view>
						<view class="quota">{{ t('market.xe') }}{{ '('+item.quota+')'}}</view>
					</view>
				</view>
				<view class="balance-box">
					<view class="balance">
						<text>{{ t('market.kyye') }}：{{formattedBalance}}</text>
						<text class="unit">USDT</text>
					</view>
					<view class="balance">
						<text>{{ t('market.yqsy') }}：</text>
						<text>{{ orderFeeData.profit ? '+' + orderFeeData.profit : '--' }}</text>
					</view>
				</view>
				<view class="amount-box">
					<view class="cost">{{ t('market.fy') }}:{{ orderFeeData.fee || '--' }}</view>
					<view class="input-box">
						<view class="border-box">
							<input type="number" v-model="amount"/>
						</view>
					</view>
					<view class="circle" @click="setMaxAmount">MAX</view>
					<view class="circle" @click="amountAdd">
						<image src="/static/icon/add.svg" mode=""></image>
					</view>
					<view class="circle" @click="amountReduce">
						<image src="/static/icon/cut.svg" mode=""></image>
					</view>
				</view>
				<view class="steps-box">
					<!-- 	<view class="step-item" v-for="(item,index) in stepsList" :key="index">
						<view class="steps"></view>
						<view class="title">{{item}}</view>
					</view> -->
					<view class="progress-wrap">
						<view class="progress-box" @click="changeProgress(0)">
							<view class="border-box" v-if="stepsActive == 1">
								<view class="start-number"></view>
							</view>
							<view v-else class="pass-number"></view>
							<view :class="['normal-desc', stepsActive > 0 ? 'active-desc' : '']">0</view>
						</view>
						<view class="progress-box" @click="changeProgress(0.25)">
							<view v-if="stepsActive == 2" class="active-number"></view>
							<view v-else-if="stepsActive >2" class="pass-number"></view>
							<view v-else class="normal-number"></view>
							<view :class="['normal-desc', stepsActive > 2 ? 'active-desc' : '']">25%</view>
						</view>
						<view class="progress-box" @click="changeProgress(0.5)">
							<view v-if="stepsActive == 3" class="active-number"></view>
							<view v-else-if="stepsActive >3" class="pass-number"></view>
							<view v-else class="normal-number"></view>
							<view :class="['normal-desc', stepsActive > 2 ? 'active-desc' : '']">50%</view>
						</view>
						<view class="progress-box" @click="changeProgress(0.75)">
							<view v-if="stepsActive == 4" class="active-number"></view>
							<view v-else-if="stepsActive >4" class="pass-number"></view>
							<view v-else class="normal-number"></view>
							<view :class="['normal-desc', stepsActive > 3 ? 'active-desc' : '']">75%</view>
						</view>
						<view class="progress-box" @click="changeProgress(1)">
							<view v-if="stepsActive == 5" class="active-number"></view>
							<view v-else-if="stepsActive >5" class="pass-number"></view>
							<view v-else class="normal-number"></view>
							<view :class="['normal-desc', stepsActive > 4 ? 'active-desc' : '']">100%</view>
						</view>
						<view class="progress-line bg1">
							<!-- <block v-if="stepsActive < 5"> -->
							<view :class="['dot', 'left1', amount==0 || stepsActive > 1 ? `w${stepsActive}` : 'w2']"></view>
							<!-- <view :class="[stepsActive > 1?'dot':'', 'left1']"></view> -->
							<!-- 								<view :class="['dot', 'w2', stepsActive > 1 ? 'left4' : 'left2']"></view>
								<view :class="['dot', 'w3', stepsActive > 1 ? 'left5' : 'left3']"></view> -->
							<!-- </block> -->
						</view>
					</view>
				</view>
				<view v-if="isUpOrDown=='1'" class="but-box" @click="confirmBut">{{ t('market.qrmz') }}</view>
				<view v-else class="down-box" @click="confirmBut">{{ t('market.qrmd') }}</view>
			</view>
		</u-popup>
		<GlobalPopup ref="popup"></GlobalPopup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted,
		watch,
		computed,
		nextTick
	} from 'vue';
	import {
		useI18n
	} from 'vue-i18n';
	import navbar from '@/components/navbar/navbar.vue';
	import GlobalPopup from '@/components/GlobalPopup/GlobalPopup.vue';
	import { optionApi, incomeApi, goodsApi } from '@/utils/api.js';
	import globalStore from '@/utils/store.js';
	import TradeComponent from '@/components/Trade/index.vue';
	import websocket from '@/utils/websocket.js'; // 引入WebSocket工具
	// 定义k线类型
	const klineType = ref('stock-kline-day');
	// 接收k线图传来的类型
	const handleKlineDataUpdate = (e) => {
		klineType.value = e;
	}
	
	const accountAmount = ref([{time:1761281760000,value:3975.4},{time:1761281820000,value:3972.4},{time:1761281880000,value:3975.4},{time:1761281940000,value:3970.4},{time:1761282000000,value:3972.4},{time:1761282060000,value:3970.4},{time:17612822120000,value:3972.4}])
	
	const {
		t,
		locale
	} = useI18n();
	
	// 全局状态管理
	const { state: globalState, getters: globalGetters, actions: globalActions } = globalStore;
	
	const stepsActive = ref(1); // 步骤条进度 1-5
	// Y轴价格显示
	const yAxisPrice = ref('');
	
	// 计算属性：判断是否显示Y轴价格区域
	// 面积图时隐藏Y轴价格显示
	const showYAxisPrice = computed(() => {
		return yAxisPrice.value !== '' && chartType.value === 'candle';
	});
	
	// 计算属性：判断是否为蜡烛图
	const isCandleChart = computed(() => {
		return chartType.value === 'candle';
	});
	// 修改为计算属性，从全局状态获取可用余额
	const balance = computed(() => globalState.availableBalance);
	const formattedBalance = computed(() => globalGetters.formattedBalance.value);
	
	// 最大可购买金额计算
	const maxPurchaseAmount = computed(() => {
		if (!balance.value || isSelectBuy.value === '' || !revenueList.value[parseInt(isSelectBuy.value)]) {
			return 0;
		}
		
		const selectedConfig = revenueList.value[parseInt(isSelectBuy.value)];
		const maxAmount = selectedConfig.maxAmount || 0;
		
		// 返回用户余额和产品最大限额中的较小值
		return Math.min(balance.value, maxAmount);
	});
	
	// 格式化的最大可购买金额
	const formattedMaxAmount = computed(() => {
		return globalStore.formatCurrency(maxPurchaseAmount.value);
	});
	
	const amount = ref(0);
	watch(amount, async (newValue, oldValue) => {
	   var p = amount.value/balance.value * 100

	   if( p < 25){
		   stepsActive.value=1
	   }else if( p < 50){
		   stepsActive.value=2
	   }else if( p < 75){
		   stepsActive.value=3
	   }else if( p < 100){
		   stepsActive.value=4
	   }else {
		   stepsActive.value=5
	   }
	   
	   // 金额变化后，如果已选择时间且金额大于0，则计算手续费
	   if (newValue > 0 && isSelectBuy.value !== '') {
		   await calculateOrderFee()
	   }
	});
	const popup = ref()
	const tradeRef = ref(null); // trade-view 组件引用
	const klineChartRef = ref(null); // K线图表组件引用
	const isCollect = ref(false);
	const favouriteId = ref(''); // 收藏ID，用于删除收藏
	const stockId = ref(''); // 产品ID
	const currentProductId = ref(''); // 当前产品ID（从路由参数获取）
	const currentProductCode = ref(''); // 当前产品代码（从路由参数获取）
	const stockDetail = ref({}); // 产品详情
	const iconPath = ref('/static/icon/btc-detail.svg'); // 动态图标路径
	const isLoadingStock = ref(false); // 产品详情加载状态
	const stockConfigData = ref({}); // 产品配置数据
	const isLoadingConfig = ref(false); // 产品配置加载状态
	const orderFeeData = ref({}); // 订单手续费数据
	const isLoadingFee = ref(false); // 手续费加载状态
	const activeTime = ref('1m');
	const chartType = ref('candle');
	const activeTab = ref('holding');
	const isLoading = ref(false); // 加载状态
	const isShowBuy = ref(false); //购买弹窗
	const refreshTimer = ref(null); // 防抖刷新定时器
	const isSelectBuy = ref('0')
	const stepsList = ref(["0", "25%", "50%", "75%", "100%"])	
	// K线数据相关
	const klineData = ref([]); // K线数据
	const isLoadingKline = ref(false); // K线加载状态
	
	// 实時数据对象（接收websocket更新）
	const realtimeData = ref({
		lastPrice: '0.00',
		open: '--',
		high: '--',
		low: '--',
		close: '--',
		changePercent: '-3.1%'
	});
	
	// 时间参数映射表
	const timeParamMap = {
		'1m': 'min1',    // 1分钟
		'5m': 'min5',    // 5分钟
		'30m': 'min30',  // 30分钟
		'60m': 'min60',  // 60分钟
		'1D': 'day',     // 1天
		'1W': 'week',    // 1周
		'1M': 'month'    // 1月
	};
	
	// 使用计算属性从stockConfigData生成revenueList
	const revenueList = computed(() => {
		if (!stockConfigData.value || !Array.isArray(stockConfigData.value)) {
			return [];
		}
		
		return stockConfigData.value.map(item => ({
			id: item.id,
			stockId: item.stockId,
			time: `${item.minute}S`, // 正确将分钟转换为秒数显示
			revenue: `${item.rate}%`, // 收益率
			quota: `${item.minAmount}-${item.maxAmount}`, // 额度范围
			minute: item.minute, // 保留原始分钟数
			second: item.minute, // 添加秒数字段
			minAmount: item.minAmount,
			maxAmount: item.maxAmount,
			rate: item.rate,
			feeRate: item.feeRate,
			minFee: item.minFee
		}));
	});
	const isUpOrDown = ref(); //买张或买跌
	// 打开买单弹窗
	const openBuyPopup = async (type) => {
		// 防止重复请求
		if (isLoadingConfig.value) {
			return;
		}
		
		isShowBuy.value = true
		isUpOrDown.value = type
		
		// 调用产品配置接口
		await getStockConfigData()
	}
	// 关闭弹窗
	const closePopup = () => {
		isShowBuy.value = false
	}
	// 选择购买
	const chooseBuy = async (index) => {
		isSelectBuy.value = index
		
		// 重置金额
		amount.value = 0
		
		// 选择时间后，如果有金额，则计算手续费
		if (amount.value > 0) {
			await calculateOrderFee()
		}
	}
	
	// MAX 按钮点击事件
	const setMaxAmount = () => {
		// 检查是否有可用的配置数据
		if (!revenueList.value || revenueList.value.length === 0) {
			uni.showToast({
				title: '配置数据加载中，请稍后',
				icon: 'none'
			});
			return;
		}
		
		if (maxPurchaseAmount.value > 0) {
			amount.value = maxPurchaseAmount.value;
		} else {
			uni.showToast({
				title: '当前无可用余额',
				icon: 'none'
			});
		}
	}
	// 确认购买
	const confirmBut = async () => {
		if (amount.value <= 0) {
			uni.showToast({
				title: '请输入购买金额',
				icon: 'none'
			});
			return;
		}
		
		if (amount.value > balance.value) {
			uni.showToast({
				title: '余额不足',
				icon: 'none'
			});
			return;
		}
		
		try {
			uni.showLoading({
				title: '下单中...'
			});
			
			// 获取选择的时间配置
			const selectedTimeConfig = revenueList.value[parseInt(isSelectBuy.value)];
			if (!selectedTimeConfig) {
				uni.hideLoading();
				uni.showToast({
					title: '请选择时间周期',
					icon: 'none'
				});
				return;
			}
			
			// 调用期权下单接口
			const orderData = {
				direction: isUpOrDown.value === '0' ? 2 : 1, // 买跌: 2, 买涨: 1
				amount: amount.value,
				productId: stockId.value, // 使用当前产品ID
				stockConfigId: selectedTimeConfig.id, // 使用选择的配置ID
				second: selectedTimeConfig.second // 使用配置中的秒数字段
			};
			
			const response = await optionApi.submitOrder(orderData);
			
			uni.hideLoading();
			
			if (response && response.code === 0) {
				uni.showToast({
					title: '下单成功',
					icon: 'success'
				});
				
				// 关闭弹窗
				isShowBuy.value = false;
				
				// 重新获取持仓数据和用户余额
				getPositionData(0);
				await globalActions.refreshBalance();
				
				// 重置金额
				amount.value = 0;
			} else {
				uni.showToast({
					title: response?.msg || '下单失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.hideLoading();

			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	}
	
	// 获取产品详情
	const getStockDetail = async () => {
		if (!stockId.value) {

			return;
		}
		
		try {
			isLoadingStock.value = true;
			const response = await goodsApi.getStockDetail(stockId.value);
			
			if (response && response.code === 0 && response.data) {
				stockDetail.value = response.data;
				// 更新收藏状态
				isCollect.value = response.data.favourite || false;
				// 保存收藏ID，用于删除收藏
				favouriteId.value = response.data.favouriteId || '';
			} else {

				uni.showToast({
					title: response?.msg || '获取产品详情失败',
					icon: 'none'
				});
			}
		} catch (error) {

			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		} finally {
			isLoadingStock.value = false;
		}
	};
	
	// 获取产品配置数据
	const getStockConfigData = async () => {
		if (!stockId.value) {

			return;
		}
		
		try {
			isLoadingConfig.value = true;
			
			// 显示加载提示（超过1秒）
			const loadingTimer = setTimeout(() => {
				if (isLoadingConfig.value) {
					uni.showLoading({
						title: '正在获取配置...',
						mask: true
					});
				}
			}, 1000);
			
			const response = await goodsApi.getStockConfigList(stockId.value);
			
			clearTimeout(loadingTimer);
			uni.hideLoading();
			
			if (response && response.code === 0 && response.data) {
				stockConfigData.value = response.data;

			} else {

				uni.showToast({
					title: response?.msg || '获取产品配置失败',
					icon: 'none',
					duration: 2000
				});
			}
		} catch (error) {
			uni.hideLoading();

			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none',
				duration: 2000
			});
		} finally {
			isLoadingConfig.value = false;
		}
	};
	
	// 计算订单手续费
	const calculateOrderFee = async () => {
		if (!stockId.value || !amount.value || isSelectBuy.value === '') {
			return;
		}
		
		// 防止重复请求
		if (isLoadingFee.value) {
			return;
		}
		
		// 获取选择的时间配置
		const selectedTimeConfig = revenueList.value[parseInt(isSelectBuy.value)];
		if (!selectedTimeConfig) {
			return;
		}
		
		try {
			isLoadingFee.value = true;
			
			// 显示加载提示（超过1秒）
			const loadingTimer = setTimeout(() => {
				if (isLoadingFee.value) {
					uni.showLoading({
						title: '正在计算费用...',
						mask: true
					});
				}
			}, 1000);
			
			const response = await optionApi.getOrderFee({
				productId: stockId.value,
				amount: amount.value,
				second: selectedTimeConfig.second, // 使用配置中的秒数字段
				direction: isUpOrDown.value === '0' ? 2 : 1, // 买跌: 2, 买涨: 1
				stockConfigId: selectedTimeConfig.id // 添加配置ID
			});
			
			clearTimeout(loadingTimer);
			uni.hideLoading();
			
			if (response && response.code === 0 && response.data) {
				orderFeeData.value = response.data;

				// 这里可以更新UI显示手续费和预期收益
			} else {

				uni.showToast({
					title: response?.msg || '获取手续费失败',
					icon: 'none',
					duration: 2000
				});
			}
		} catch (error) {
			uni.hideLoading();

			uni.showToast({
				title: '获取手续费失败，请重试',
				icon: 'none',
				duration: 2000
			});
		} finally {
			isLoadingFee.value = false;
		}
	};
	
	// 切换收藏状态
	const changeCollect = async () => {
		if (!stockId.value) {
			uni.showToast({
				title: '产品ID不能为空',
				icon: 'none'
			});
			return;
		}
		
		try {
			uni.showLoading({
				title: isCollect.value ? '取消收藏中...' : '收藏中...'
			});
			
			if (isCollect.value) {
				// 当前是收藏状态，执行取消收藏
				const response = await goodsApi.deleteStockFavorite(favouriteId.value);
				if (response && response.code === 0) {
					isCollect.value = false;
					// 重新获取股票详情以更新favouriteId
					await getStockDetail();
					uni.showToast({
						title: '取消收藏成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: response?.msg || '取消收藏失败',
						icon: 'none'
					});
				}
			} else {
				// 当前是未收藏状态，执行收藏
				const response = await goodsApi.createStockFavorite({
					stockId: stockId.value
				});
				if (response && response.code === 0) {
					isCollect.value = true;
					// 重新获取股票详情以更新favouriteId
					await getStockDetail();
					uni.showToast({
						title: '收藏成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: response?.msg || '收藏失败',
						icon: 'none'
					});
				}
			}
		} catch (error) {

			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};

	// 格式化涨跌百分比
	const formatChangePercent = (changePercent) => {
		if (changePercent === null || changePercent === undefined) {
			return '-3.1%'; // 默认值
		}
		const num = parseFloat(changePercent);
		if (isNaN(num)) {
			return '-3.1%'; // 默认值
		}
		return num > 0 ? `+${num}%` : `${num}%`;
	};

	// 获取涨跌样式类
	const getChangeClass = (changePercent) => {
		if (changePercent === null || changePercent === undefined) {
			return 'change-down'; // 默认为下跌样式
		}
		const num = parseFloat(changePercent);
		if (isNaN(num)) {
			return 'change-down'; // 默认为下跌样式
		}
		return num > 0 ? 'change-up' : 'change-down';
	};

	// 设置时间周期
	const setActiveTime = async (time) => {

		activeTime.value = time;

		// \u83b7\u53d6\u5bf9\u5e94\u65f6\u95f4\u7684K\u7ebf\u6570\u636e
		await getKlineData(time);
	};
	
	// \u83b7\u53d6K\u7ebf\u6570\u636e
	const getKlineData = async (timeParam) => {
		if (!stockId.value) {

			return;
		}
		
		try {
			isLoadingKline.value = true;
			
			// \u6839\u636e\u65f6\u95f4\u53c2\u6570\u6620\u5c04\u5230API\u53c2\u6570
			const klt = timeParamMap[timeParam] || 'day';

			const response = await goodsApi.getCommonKline({
				id: stockId.value,
				klt: klt
			}, {
				timeout: 30000
			});
			
			if (response && response.code === 0 && response.data) {

				// \u5148\u521d\u59cb\u5316\u5b9e\u6642\u6570\u636e\uff08\u4ece market\u5b57\u6bb5\uff09
				if (response.data.market) {
					realtimeData.value = {
						lastPrice: response.data.market.lastPrice || '0.00',
						open: response.data.market.open || '--',
						high: response.data.market.high || '--',
						low: response.data.market.low || '--',
						close: response.data.market.close || '--',
						changePercent: response.data.market.changePercent || '-3.1%'
					};

				}
				
				// \u8f6cK\u7ebf\u6570\u636e\u683c\u5f0f\uff08\u6839\u636e\u56fe\u8868\u7c7b\u578b\u8f6c\u6362\uff09
				if (response.data.klines && Array.isArray(response.data.klines)) {
					if (chartType.value === 'candle') {
						// \u84b7\u70db\u56fe\u683c\u5f0f\uff1a\u9700\u8981open, high, low, close, volume
						klineData.value = response.data.klines.map(item => ({
							time: parseInt(item.timestamp) * 1000, // \u79d2\u8f6c\u6beb\u79d2
							open: parseFloat(item.open),
							high: parseFloat(item.high),
							low: parseFloat(item.low),
							close: parseFloat(item.close),
							volume: parseFloat(item.volume)
						}));

					} else {
						// \u9762\u79ef\u56fe\u683c\u5f0f\uff1a\u4ec5\u9700\u8981time\u548cvalue
						klineData.value = response.data.klines.map(item => ({
							time: parseInt(item.timestamp) * 1000, // \u79d2\u8f6c\u6beb\u79d2
							value: parseFloat(item.close) // \u4f7f\u7528\u6536\u76d8\u4ef7\u4f5c\u4e3aK\u7ebf\u503c
						}));

					}

				} else {

					klineData.value = [];
				}
			} else {

				uni.showToast({
					title: response?.msg || '\u83b7\u53d6K\u7ebf\u6570\u636e\u5931\u8d25',
					icon: 'none'
				});
				klineData.value = [];
			}
		} catch (error) {

			uni.showToast({
				title: '\u7f51\u7edc\u9519\u8bef\uff0c\u8bf7\u91cd\u8bd5',
				icon: 'none'
			});
			klineData.value = [];
		} finally {
			isLoadingKline.value = false;

		}
	};

	// 监听K线数据变化
	watch(klineData, (newVal) => {

	}, { deep: true });

	// WebSocket消息处理：实时更新K线数据
	const handleWebSocketMessage = (message) => {
		try {
			// 根据当前时间周期匹配对应的消息类型
			const getExpectedMessageType = (time) => {
				switch (time) {
					case '1m': return 'stock-kline-min1';
					case '5m': return 'stock-kline-min5';
					case '30m': return 'stock-kline-min30';
					case '60m': return 'stock-kline-min60';
					case '1D': return 'stock-kline-day';
					case '1W': return 'stock-kline-week';
					case '1M': return 'stock-kline-month';
					default: return 'stock-kline-min1';
				}
			};

			// 检查消息类型是否匹配当前时间周期
			const expectedType = getExpectedMessageType(activeTime.value);
			if (message.type !== expectedType) {
				return;
			}

			// 解析消息内容：双层JSON字符串格式
			let content = message.content;

			// 第一层解析
			if (typeof content === 'string') {
				content = JSON.parse(content);
			}

			// 第二层解析（如果内容本身还是字符串）
			if (typeof content === 'string') {
				content = JSON.parse(content);
			}

			// 检查产品ID是否匹配 - 比较content.id和当前stockId
			if (!content || !content.id || content.id !== parseInt(stockId.value)) {
				return;
			}

			// 更新市场实时数据（保持响应性）
			if (content.market) {
				realtimeData.value.lastPrice = content.market.lastPrice || realtimeData.value.lastPrice;
				realtimeData.value.open = content.market.open || realtimeData.value.open;
				realtimeData.value.high = content.market.high || realtimeData.value.high;
				realtimeData.value.low = content.market.low || realtimeData.value.low;
				realtimeData.value.close = content.market.close || realtimeData.value.close;
				realtimeData.value.changePercent = content.market.changePercent !== undefined && content.market.changePercent !== null ? content.market.changePercent : realtimeData.value.changePercent;
			}

			// 处理K线数据 - 检查是否有klines数据
			if (content.klines && Array.isArray(content.klines) && content.klines.length > 0) {
				// 采用逐条处理方式，使用响应式方法更新数据
				content.klines.forEach(item => {
					// 转换数据格式（根据图表类型）
					let newBar;
					if (chartType.value === 'candle') {
						// 蜡烛图格式
						newBar = {
							time: parseInt(item.timestamp) * 1000,
							open: parseFloat(item.open),
							high: parseFloat(item.high),
							low: parseFloat(item.low),
							close: parseFloat(item.close),
							volume: parseFloat(item.volume)
						};
					} else {
						// 面积图格式
						newBar = {
							time: parseInt(item.timestamp) * 1000,
							value: parseFloat(item.close)
						};
					}

					// 使用响应式方法更新K线数据数组（逐条渲染）
					if (klineData.value.length > 0) {
						const lastBar = klineData.value[klineData.value.length - 1];
						if (lastBar.time === newBar.time) {
							// 替换最后一条K线（同一时间内的更新）- 使用splice保持响应性
							klineData.value.splice(klineData.value.length - 1, 1, newBar);
						} else {
							// 添加新的K线（新的时间段开始）- 使用push保持响应性
							klineData.value.push(newBar);
						}
					} else {
						// 数据为空，直接添加
						klineData.value.push(newBar);
					}
				});
			}
		} catch (error) {
			// 静默失败，不输出错误
		}
	};
	// 显示技术指标
	const showIndicators = () => {
		uni.showToast({
			title: '技术指标功能开发中',
			icon: 'none'
		});
	};

	// 设置图表类型
	const setChartType = async (type) => {

		// 先更新图表类型
		chartType.value = type;
		
		// 切换图表类型后，重新获取对应格式的K线数据
		// 因为蜡烛图需要{open,high,low,close}，面积图需要{value}
		// 两种格式不能互相转换，必须从接口重新获取
		await getKlineData(activeTime.value);

	};

	// 增加购买数量
	const amountAdd = () => {
		if (amount.value < balance.value) {
			amount.value += 10;
		}
	};

	// 减少购买数量
	const amountReduce = () => {
		if (amount.value > 0) {
			amount.value -= 10;
		}
	};

	// 改变进度条
	const changeProgress = (progress) => {
		const newAmount = Math.ceil(balance.value * progress);
		amount.value = Math.min(newAmount, balance.value);
	};

	// 跳转到持仓详情
	const goToPositionDetail = (id) => {
		uni.navigateTo({
			url: `/pages/position/details?id=${id}`
		});
	};

	// 设置活动标签
	const setActiveTab = (tab) => {
		activeTab.value = tab;
		// 根据标签获取对应的数据
		if (tab === 'holding') {
			getPositionData(0); // 获取持仓中数据
		} else if (tab === 'closed') {
			getPositionData(1); // 获取已平仓数据
		}
	};

	// 获取持仓数据
	const getPositionData = async (status) => {
		try {
			isLoading.value = true;
			const params = {
				status: status, // 0: 持仓中, 1: 已平仓
				pageNo: 1,
				pageSize: 20
			};
			const response = await optionApi.getOrderPage(params);
			if (response && response.data) {
				const list = response.data.list || [];
				// 处理数据格式，确保与模板字段匹配，保留id字段用于跳转
				// 清除之前的倒计时
				clearAllCountdowns();
				
				positionList.value = list.map(item => {
					const remainingSeconds = item.remainingSeconds || item.second || 0;
					const totalSeconds = item.totalSeconds || item.duration || item.second || 0;
					
					// 判断是否为已平仓订单
					const isClosed = status === 1;
					
					return {
						id: item.id, // 保留原始id字段用于跳转
						symbol: item.symbol || item.tradingPair || 'BTC/USDT',
						direction: item.direction || item.type || 1, // 1: 涨, 2: 跌
						time: isClosed ? '结束' : formatCountdown(remainingSeconds), // 已平仓显示"结束"
						remainingSeconds: isClosed ? 0 : remainingSeconds, // 已平仓剩余秒数为0
						totalSeconds: totalSeconds, // 总秒数
						openPrice: item.buyPrice || item.openPrice || item.price || '0.00', // 修正：使用buyPrice作为开仓价格
						amount: item.amount || item.quantity || '0',
						profitRate: (() => {
							// 优先使用profitRatio字段，确保格式化为带正负号的字符串
							const ratio = item.profitRatio || item.profitRate || item.profit || 0;
							const numRatio = parseFloat(ratio);
							return numRatio > 0 ? `+${numRatio}%` : `${numRatio}%`;
						})(), // 修正：使用profitRatio作为收益率，确保格式化
						floatingProfit: (() => {
							// 确保浮动收益格式化为带正负号的字符串
							const profit = item.floatingProfit || item.profit || 0;
							const numProfit = parseFloat(profit);
							return numProfit > 0 ? `+${numProfit}` : `${numProfit}`;
						})(),
						progressWidth: isClosed ? '100%' : (totalSeconds > 0 ? `${Math.min(100, Math.max(0, ((totalSeconds - remainingSeconds) / totalSeconds) * 100))}%` : '0%'), // 已平仓进度条拉满
						progressTime: item.progressTime || item.remainingTime || '0s'
					};
				});
				
				// 只为持仓中的订单启动倒计时
				if (status === 0) {
					positionList.value.forEach(item => {
						if (item.remainingSeconds > 0) {
							startCountdown(item.id, item.remainingSeconds);
						}
					});
				}
			}
		} catch (error) {

		} finally {
			isLoading.value = false;
		}
	};

	// 持仓数据列表
	const positionList = ref([]);
	
	// 倒计时定时器
	const countdownTimers = ref(new Map());
	
	// 格式化倒计时显示
	const formatCountdown = (seconds) => {
		if (seconds <= 0) return '0s';
		return `${seconds}s`;
	};
	
	// 防抖刷新持仓列表
	const debounceRefreshPositions = () => {
		// 清除之前的定时器
		if (refreshTimer.value) {
			clearTimeout(refreshTimer.value);
		}
		
		// 设置新的定时器，延迟2秒刷新
		refreshTimer.value = setTimeout(async () => {
			// 只有在当前标签是"持仓中"时才刷新
			if (activeTab.value === 'holding') {

				// 显示刷新提示
				uni.showToast({
					title: '订单已完成，正在刷新...',
					icon: 'none',
					duration: 1500
				});
				
				// 刷新持仓数据
				await getPositionData(0);

			}
			refreshTimer.value = null;
		}, 2000);
	};
	
	// 启动倒计时
	const startCountdown = (itemId, remainingSeconds) => {
		// 清除已存在的定时器
		if (countdownTimers.value.has(itemId)) {
			clearInterval(countdownTimers.value.get(itemId));
		}
		
		let currentSeconds = remainingSeconds;
		
		const timer = setInterval(() => {
			currentSeconds--;
			
			// 更新对应项目的时间显示
			const item = positionList.value.find(pos => pos.id === itemId);
			if (item) {
				item.time = formatCountdown(currentSeconds);
				item.remainingSeconds = currentSeconds;
				
				// 计算进度条宽度
				if (item.totalSeconds > 0) {
					const progress = ((item.totalSeconds - currentSeconds) / item.totalSeconds) * 100;
					item.progressWidth = `${Math.min(100, Math.max(0, progress))}%`;
				}
			}
			
			// 倒计时结束
			if (currentSeconds <= 0) {
				clearInterval(timer);
				countdownTimers.value.delete(itemId);

				// 使用防抖刷新函数，避免多个订单同时结束时重复刷新
				debounceRefreshPositions();
			}
		}, 1000);
		
		countdownTimers.value.set(itemId, timer);
	};
	
	// 清除所有倒计时
	const clearAllCountdowns = () => {
		countdownTimers.value.forEach(timer => clearInterval(timer));
		countdownTimers.value.clear();
	};

	// 获取用户信息和可用余额
	const getUserTotalProfit = async () => {
		try {
			await globalActions.fetchUserInfo();
		} catch (error) {

		}
	};

	// 页面初始化
	onMounted(() => {

		// 初始化全局状态
		globalActions.initUserInfo();
		
		// 获取页面参数中的产品ID
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.options;
		
		// 从路由参数获取产品ID和产品代码
		if (options && (options.productId || options.id)) {
			stockId.value = options.productId || options.id;
			currentProductId.value = options.productId || options.id;
			// 如果有产品代码，也保存起来
			if (options.productCode) {
				currentProductCode.value = options.productCode;

			} else {
				// 如果没有产品代码，使用默认值
				currentProductCode.value = 'ETHUSDT';
			}
			// 获取图标路径
			if (options.iconPath) {
				iconPath.value = decodeURIComponent(options.iconPath);
			}
			// 获取产品详情
			getStockDetail();
		} else {
			// 如果没有传递产品ID，使用默认值或显示错误

			stockId.value = '1'; // 默认产品ID
			currentProductId.value = 'ETH';
			currentProductCode.value = 'ETHUSDT';
			getStockDetail();
		}
		
		// ... existing code ...
		
		// 默认加载持仓中的数据
		getPositionData(0);
		// 获取用户总收益
		getUserTotalProfit();
		// 加载初始化的K线数据（默认为1分钟）
		getKlineData('1m').then(() => {

		});
		
		// 设置WebSocket消息监听
		websocket.addMessageListener(handleWebSocketMessage);

	});
	
	// 页面卸载时清除值计是和WebSocket消息监听
	onUnmounted(() => {
		clearAllCountdowns();
		// 清除防抱刷新定时器
		if (refreshTimer.value) {
			clearTimeout(refreshTimer.value);
			refreshTimer.value = null;
		}
		// 移除WebSocket消息监听
		websocket.removeMessageListener(handleWebSocketMessage);

	});
	
	// 处理K线图点击事件
	const handleKlineClick = (data) => {
		// 根据图表类型更新Y轴价格显示
		if (data.type === 'candle') {
			// 蜡烛图：显示最高价、最低价、开盘价、收盘价和时间
			const high = typeof data.high === 'number' ? data.high.toFixed(2) : data.high;
			const low = typeof data.low === 'number' ? data.low.toFixed(2) : data.low;
			const open = typeof data.open === 'number' ? data.open.toFixed(2) : data.open;
			const close = typeof data.close === 'number' ? data.close.toFixed(2) : data.close;
			
			// 格式化时间显示
			let timeStr = '';
			if (typeof data.time === 'number') {
				const date = new Date(data.time * 1000);
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				timeStr = `${month}-${day} ${hours}:${minutes}`;
			} else {
				timeStr = data.time || '';
			}
			
			yAxisPrice.value = `高:${high} 低:${low} 开:${open} 收:${close} 时间:${timeStr}`;
		}
	};
	
	// 处理价格高亮事件
	const handlePriceHighlight = (price) => {
		console.log('[价格高亮] 当前价格:', price);
		// 更新Y轴价格显示
		if (typeof price === 'number') {
			yAxisPrice.value = price.toFixed(2);
		} else {
			yAxisPrice.value = price;
		}
	};
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #F5F6FA;
		padding: 0 0 100rpx;
		box-sizing: border-box;
	}

	.left-icon {
		width: 20.93rpx;
		height: 20.93rpx;
		line-height: 20.93rpx;

		image {
			width: 20.93rpx;
			height: 20.93rpx;
		}
	}

	.collect-icon {
		width: 34.89rpx;
		height: 34.89rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.icon {
			width: 34.89rpx;
			height: 34.89rpx;
		}
	}

	.title-box {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.title {
			font-size: 38.37rpx;
			font-weight: 500;
			letter-spacing: 0rpx;
			line-height: 55.57rpx;
			color: rgba(255, 255, 255, 1);
		}

		.change-box {
			font-size: 24.42rpx;
			color: rgba(255, 255, 255, 1);
			font-weight: 500;
			line-height: 35.36rpx;

			.change {
				color: rgba(247, 56, 79, 1);
			}
			
			.change-up {
				color: rgba(47, 194, 91, 1) !important; /* 上涨绿色 */
			}
			
			.change-down {
				color: rgba(247, 56, 79, 1) !important; /* 下跌红色 */
			}
		}

	}

	.price-info {
		background-color: rgba(48, 129, 236, 1);
		padding: 120rpx 34.89rpx 61.06rpx;
		margin-top: -60rpx;
		color: #fff;
		position: relative;
		z-index: 1;

		.coin-icon {
			position: absolute;
			left: 90.70rpx;
			top: 70rpx;
			border-radius: 50%;
			background-color: #FFA500;
			display: flex;
			align-items: center;
			justify-content: center;

			.icon {
				width: 83.73rpx;
				height: 83.73rpx;
			}
		}

		.info-box {
			border-radius: 26.16rpx;
			background: rgba(255, 255, 255, 0.2);
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 31.4rpx 38.38rpx;
			background-image: url(/static/icon/detail-line.svg);
			background-position: 161.73rpx center;
			background-repeat: no-repeat;


			.price-value {
				text-shadow: 0rpx 3.49rpx 6.98rpx rgba(0, 0, 0, 0.25);
				/** 文本1 */
				font-size: 45.35rpx;
				font-weight: 500;
			}

			.price-details {
				display: flex;
				flex-direction: column;
				gap: 17.45rpx;

				.price-row {
					display: flex;
					align-items: center;
					font-size: 20.93rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 30.32rpx;
					color: rgba(255, 255, 255, 1);
					text-align: left;

					.label {
						// font-size: 24rpx;
						// margin-right: 10rpx;
						margin-left: 17.45rpx;
					}

					.value {
						// font-size: 24rpx;
					}
				}
			}
		}

	}

	.time-selector {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 20.93rpx;
		margin-bottom: -100rpx;
		padding: 27.91rpx 43.61rpx;
		border-radius: 15.7rpx;
		background: rgba(255, 255, 255, 1);
		box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(0, 0, 0, 0.25);

		.time-item {
			font-size: 24.42rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			line-height: 35.36rpx;
			color: rgba(0, 0, 0, 1);

			&.active {
				font-size: 24.42rpx;
				font-weight: 500;
				letter-spacing: 0rpx;
				line-height: 35.36rpx;
				color: rgba(45, 152, 235, 1);
			}
		}

		// .chart-type {
		// 	display: flex;
		// 	align-items: center;
		// 	gap: 20rpx;

		.chart-icon {
			width: 41.86rpx;
			height: 32.56rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.icon {
				width: 41.86rpx;
				height: 32.56rpx;
			}

			&.active {
				// background-color: #EAEAEA;
				// border-radius: 6rpx;
			}
		}

		// }
	}

	.chart-container {
		width: 750.04rpx;
		height: 601.78rpx;
		background-color: #fff;
		position: relative;

		image {
			width: 100%;
			height: 100%;
		}
		a {
		display: none !important;
		}

		::v-deep a {
			display: none !important;
		}

		:deep(a) {
			display: none !important;
		}
	}
	
	/* Y轴价格显示区域 */
	.y-axis-price {
		position: absolute;
		top: 20rpx;
		border-radius: 8rpx;
		padding: 10rpx 15rpx;
		font-size: 16rpx;
		color: #f86868;
		font-weight: 500;
		z-index: 10;
	}

	.position-tabs {
		display: flex;
		align-items: center;
		border-radius: 1742.54rpx;
		box-sizing: border-box;
		margin: 22.68rpx 43.61rpx 27.91rpx;
		padding: 1px;
		background: linear-gradient(90deg, rgba(14, 194, 157, 1) 0%, rgba(88, 218, 221, 1) 35.42%, rgba(25, 162, 203, 1) 68.75%, rgba(2, 124, 217, 1) 100%);
		border-radius: 1742.54rpx;

		.border-box {
			width: 662.83rpx;
			display: flex;
			align-items: center;
			border-radius: 1742.54rpx;
			box-sizing: border-box;
			border-radius: 1742.54rpx;
			padding: 10.67rpx;
			background-color: #ffffff;

			.tab {
				flex: 1;
				text-align: center;
				font-size: 27.91rpx;
				font-weight: 500;
				line-height: 80.24rpx;
				color: rgba(102, 102, 102, 1);
				position: relative;
				height: 80.24rpx;

				&.active {
					border-radius: 1742.54rpx;
					background: linear-gradient(90deg, rgba(12, 193, 155, 1) 0%, rgba(91, 220, 222, 1) 15.97%, rgba(5, 145, 198, 1) 65.97%, rgba(2, 120, 220, 1) 100%);
					color: rgba(255, 255, 255, 1);
				}
			}
		}


	}

	.position-list {
		margin: 0 34.89rpx;
		padding-bottom: 100rpx;

		.empty-container {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 200rpx;
			text-align: center;
			
			text {
				font-size: 28rpx;
				color: #999999;
			}
		}

		.position-item {
			border-radius: 20.93rpx;
			box-shadow: 1.74rpx 1.74rpx 5.23rpx rgba(102, 102, 102, 0.25);
			margin-bottom: 20.93rpx;
			padding: 34.89rpx;
			background-color: #fff;

			&:last-child {
				border-bottom: none;
			}

			.position-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20.93rpx;

				.symbol-info {
					display: flex;
					align-items: center;

					.symbol {
						font-size: 27.91rpx;
						font-weight: 500;
						color: rgba(51, 51, 51, 1);
						margin-right: 10rpx;
					}

					.direction-tag {
						width: 30rpx;
						height: 30rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

					.progress-time {
						font-size: 24rpx;
						color: #999999;
					}
				}

				.right {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.progress-bar {
						width: 143rpx;
						height: 6rpx;
						background: rgba(235, 235, 235, 1);
						border-radius: 1742.54rpx;

						.progress-fill {
							height: 100%;
							background: linear-gradient(90deg, rgba(22, 196, 163, 1) 0%, rgba(74, 214, 207, 1) 34.72%, rgba(18, 156, 202, 1) 65.97%, rgba(2, 123, 217, 1) 100%);
						}
					}

					.time-info {
						font-size: 24.42rpx;
						font-weight: 500;
						color: rgba(0, 0, 0, 1);
						margin-left: 22.68rpx;
					}
				}
			}

			.position-details {
				display: flex;
				justify-content: space-between;

				.detail-column {
					display: flex;
					flex-direction: column;
					text-align: center;

					.label {
						font-size: 27.91rpx;
						font-weight: 300;
						letter-spacing: 0rpx;
						line-height: 40.42rpx;
						color: rgba(0, 0, 0, 1);
						margin-bottom: 8rpx;
					}

					.value {
						font-size: 24.42rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						line-height: 35.36rpx;
						color: rgba(51, 51, 51, 1);

						&.profit {
							color: rgba(13, 179, 100, 1);
						}

						&.loss {
							color: rgba(247, 56, 79, 1);
						}

						&.ping {
							color: rgba(42, 130, 228, 1);
						}
					}
				}
			}
		}
	}

	.trade-buttons {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 38.38rpx 75.01rpx 31.4rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		border-radius: 31.4rpx 31.4rpx 0rpx 0rpx;
		background: rgba(255, 255, 255, 1);
		backdrop-filter: blur(13.95rpx);

		.buy-button,
		.sell-button {
			width: 279.09rpx;
			height: 87.21rpx;
			line-height: 87.21rpx;
			border-radius: 26.16rpx;
			display: flex;
			justify-content: center;
			font-size: 27.91rpx;
			font-weight: 500;
			color: rgba(255, 255, 255, 1);
		}

		.buy-button {
			background: rgba(48, 129, 236, 1);
		}

		.sell-button {
			background: rgba(247, 56, 79, 1);
		}
	}

	.popup-box {
		padding: 31.4rpx 34.89rpx 69.77rpx;

		.top-icon {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 87.21rpx;
			height: 10.47rpx;
			border-radius: 1742.54rpx;
			margin: 0 auto;
			background: rgba(2, 123, 217, 1);
		}

		.top {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 52.33rpx;
			margin-bottom: 48.85rpx;

			.left {
				display: flex;
				align-items: center;

				image {
					width: 83.73rpx;
					height: 83.73rpx;
					margin-right: 17.45rpx;
				}

				.name-box {
					.name {
						font-size: 31.4rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						line-height: 45.46rpx;
						color: rgba(0, 0, 0, 1);
					}

					.change {
						font-size: 24.42rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 35.36rpx;
						color: rgba(247, 56, 79, 1);
					}
					
					.change-up {
						color: rgba(47, 194, 91, 1) !important; /* 上涨绿色 */
					}
					
					.change-down {
						color: rgba(247, 56, 79, 1) !important; /* 下跌红色 */
					}
				}
			}

			.right {
				.price {
					font-size: 31.4rpx;
					font-weight: 500;
					letter-spacing: 0rpx;
					line-height: 45.46rpx;
					color: rgba(18, 24, 38, 1);
				}

				.buy-text {
					display: flex;
					align-items: center;

					image {
						width: 27.91rpx;
						height: 27.91rpx;
						margin-left: 10rpx;
					}
				}
			}
		}

		.middle-box {
			display: flex;
			flex-wrap: wrap;
			gap: 32.89rpx;

			.item-box {
				width: 315rpx;
				// height: 139.54rpx;
				border-radius: 13.95rpx;
				border: 1.74rpx solid rgba(48, 129, 236, 1);
				text-align: center;
				padding: 17.45rpx 0;
				color: rgba(51, 51, 51, 1);

				&.active {
					color: #fff;
					background: linear-gradient(90deg, rgba(19, 195, 161, 1) 0%, rgba(70, 201, 216, 1) 36.8%, rgba(20, 158, 202, 1) 67.37%, rgba(2, 123, 217, 1) 100%);
				}

				.time {
					font-size: 31.4rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 45.46rpx;
				}

				.revenue {
					font-size: 20.93rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 30.32rpx;
				}

				.quota {
					font-size: 20.93rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 30.32rpx;
				}
			}
		}

		.balance-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin: 31.4rpx 0;

			.balance {
				font-size: 24.42rpx;
				font-weight: 400;
				letter-spacing: 0rpx;
				line-height: 35.36rpx;
				color: rgba(57, 65, 80, 1);
			}

			.unit {
				font-size: 20.93rpx;
				font-weight: 400;
				letter-spacing: 0rpx;
				line-height: 30.32rpx;
				color: rgba(57, 65, 80, 1);
				margin-left: 4rpx;
			}
		}

		.amount-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 52.33rpx;

			.cost {
				width: 143.03rpx;
				height: 69.77rpx;
				line-height: 69.77rpx;
				border-radius: 1742.54rpx;
				border: 1.74rpx solid rgba(102, 102, 102, 1);
				text-align: center;
				font-size: 20.93rpx;
				font-weight: 400;
				letter-spacing: 0rpx;
				color: rgba(102, 102, 102, 1);
			}

			.input-box {
				padding: 2rpx;
				width: 252.92rpx;
				height: 69.77rpx;
				border-radius: 1742.54rpx;
				box-sizing: border-box;
				background: linear-gradient(90deg, rgba(14, 194, 157, 1) 0%, rgba(88, 218, 221, 1) 35.42%, rgba(25, 162, 203, 1) 68.75%, rgba(2, 124, 217, 1) 100%);

				.border-box {
					width: 100%;
					height: 100%;
					border-radius: 1742.54rpx;
					// border-image: linear-gradient(90deg, rgba(14, 194, 157, 1) 0%, rgba(88, 218, 221, 1) 35.42%, rgba(25, 162, 203, 1) 68.75%, rgba(2, 124, 217, 1) 100%) 1.74;
					background-color: #fff;

					input {
						width: 252.92rpx;
						height: 69.77rpx;
						text-align: center;
					}
				}
			}

			.circle {
				width: 69.77rpx;
				height: 69.77rpx;
				line-height: 69.77rpx;
				border-radius: 1742.54rpx;
				text-align: center;
				border: 1.74rpx solid rgba(51, 51, 51, 1);
				font-size: 20.93rpx;
				color: rgba(51, 51, 51, 1);

				image {
					width: 19.77rpx;
					height: 19.77rpx;
				}
			}
		}

		.steps-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			// margin: 0 74rpx;
			margin-left: 20rpx;

			.progress-wrap {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 56rpx;
				position: relative;

				.progress-box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: space-between;
					width: 108.14rpx;

					.border-box {
						width: 20.93rpx;
						height: 20.93rpx;
						box-sizing: border-box;
						border-radius: 50%;
						background: linear-gradient(90deg, rgba(34, 192, 162, 1) 0%, rgba(67, 195, 198, 1) 34.73%, rgba(39, 162, 200, 1) 70.14%, rgba(19, 130, 210, 1) 100%);
						margin-bottom: 12rpx;
						margin-top: 6rpx;
						position: relative;
						z-index: 5;

						.start-number {
							width: 14rpx;
							height: 14rpx;
							background-color: #fff;
							border-radius: 50%;
							position: absolute;
							left: 50%;
							top: 50%;
							transform: translate(-50%, -50%);
						}
					}

					.pass-number {
						width: 20.93rpx;
						height: 20.93rpx;
						opacity: 1;
						background: rgba(34, 193, 163, 1);
						border-radius: 50%;
						z-index: 999;
						margin-bottom: 10rpx;
						margin-top: 6rpx;
						position: relative;
						z-index: 5;
					}


					.normal-number {
						width: 20.93rpx;
						height: 20.93rpx;
						border: 1.74rpx solid rgba(51, 51, 51, 1);
						// background: rgba(34, 193, 163, 1);
						border-radius: 50%;
						background: #ffffff;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-bottom: 10rpx;
						margin-top: 6rpx;
						position: relative;
						z-index: 5;
					}

					.normal-desc {
						font-size: 20.93rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 30.32rpx;
						color: rgba(102, 102, 102, 1);
					}

					.active-number {
						width: 22.93rpx;
						height: 22.93rpx;
						box-sizing: border-box;
						border-radius: 50%;
						// background: linear-gradient(90deg, rgba(34, 192, 162, 1) 0%, rgba(67, 195, 198, 1) 34.73%, rgba(39, 162, 200, 1) 70.14%, rgba(19, 130, 210, 1) 100%);
						background: rgba(255, 255, 255, 1.0);
						border: 5.23rpx solid rgba(17, 127, 211, 1);
						color: #fff;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-bottom: 12rpx;
						margin-top: 6rpx;
						position: relative;
						z-index: 5;
					}

					// .active-desc {
					// 	color: #2d2f37;
					// }
				}

				.progress-line {
					position: absolute;
					// left: 113.38rpx;
					left: 100rpx;
					right: 108rpx;
					top: 15rpx;
					width: 453rpx;
					height: 3.49rpx;
					z-index: 2;
				}

				.bg1 {
					background: rgba(51, 51, 51, 1);
				}

				.bg2 {
					background: #fe7777;
				}

				// 已过进度
				.dot {
					position: absolute;
					top: 0;
					height: 3.49rpx;
					border-radius: 4rpx;
					background: #fe7777;
					background: linear-gradient(90deg, rgba(95, 215, 216, 1) 0%, rgba(101, 193, 216, 1) 100%);
					z-index: 99;
				}

				.w1 {
					width: 0;
				}

				.w2 {
					width: (108.14rpx*1);
				}

				.w3 {
					width: (108.14rpx*2);
				}

				.w4 {
					width: (108.14rpx*3);
				}

				.w5 {
					width: (108.14rpx*4);
				}
			}
		}

		.but-box,
		.down-box {
			width: 570.38rpx;
			height: 97.68rpx;
			border-radius: 26.16rpx;
			text-align: center;
			background: rgba(48, 129, 236, 1);
			font-size: 31.4rpx;
			line-height: 97.68rpx;
			color: rgba(255, 255, 255, 1);
			margin: 52.33rpx auto;
		}

		.down-box {
			background: rgba(247, 56, 79, 1);
		}
	}
</style>